﻿using Newtonsoft.Json;
using ShineTech.Web.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShineTech.Web.Helpers
{
    public class TokenHelper
    {
        public static string CreateToken(UserDTO userDto)
        {
            try
            {
                var jwtTimestmp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); //生成token时间戳                

                var encodedString =
                    $"{ConvertHelper.ConverBase64String(jwtTimestmp)}." +
                    $"{ConvertHelper.ConverBase64String(JsonConvert.SerializeObject(userDto))}"; //连接时间戳和dtunionid

                const string sha256Secret = "sha256"; //读到h256签名私钥
                var signature = ConvertHelper.HMACSHA256(encodedString, sha256Secret); //签名
                var token = $"{encodedString}.{signature}"; //连接时间戳 user info 和签名

                //Console.WriteLine(@"token已存入redis");
                return token;
            }
            catch (Exception e)
            {
                //TODO 补充错误日志
                Console.WriteLine($@"生成token出错{e.Message} {e.InnerException}");
                return "";
            }
        }
        /// <summary>
        /// 验证token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool Validate(string token)
        {
            var userDto = TokenPart2User(token);
            var thisToken = SessionServer.Get(userDto.Id);
            return token.Equals(thisToken);

        }

        public static UserDTO Token2UserInfo(string token)
        {
            if (string.IsNullOrWhiteSpace(token))
            { return null; }
            var jwtToken = token.Split('.');
            if (jwtToken.Length != 3) return null;
            var userDto = TokenPart2User(jwtToken[1]);
            return userDto;
        }

        /// <summary>
        /// token中的第二部分转换为user
        /// </summary>
        /// <param name="tokenPart2"> token中的第二部分</param>
        /// <returns>userId</returns>
        public static UserDTO TokenPart2User(string tokenPart2)
        {
            var userJsonstring = Encoding.UTF8.GetString(Convert.FromBase64String(tokenPart2));
            var userDto = JsonConvert.DeserializeObject<UserDTO>(userJsonstring);
            return userDto;
        }

        public static DateTime Token2DateTime(string token)
        {
            var timeStr = Encoding.UTF8.GetString(Convert.FromBase64String(token.Split(".")[0]));
            DateTime.TryParse(timeStr, out var timestmp);
            return timestmp;
        }
    }
}
